package com.gta.edu.sdk.job.logtranfer;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;

public class Scpclient {

    private static final org.apache.log4j.Logger log= org.apache.log4j.Logger.getLogger(Scpclient.class);

    private String ip;
    private int port;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private static Scpclient instance;

    private static Connection conn;//scp杩炴帴

    public static synchronized Scpclient getInstance(String IP, int port, String username, String passward) {
        if (instance == null) {
            instance = new Scpclient(IP, port, username, passward);
        }
        return instance;
    }

    public Scpclient(String IP, int port, String username, String passward) {
        this.ip = IP;
        this.port = port;
        this.username = username;
        this.password = passward;
    }

    /**
     * 涓婁紶鏂囦欢锛屼笂浼犳枃浠舵椂杩涜杩炴帴鐧诲綍绛夋搷浣�
     *
     * @param localFile
     * @param remoteFileName
     * @param remoteTargetDirectory
     * @param mode
     */
    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated == false) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            if ((mode == null) || (mode.length() == 0)) {
                mode = "0600";
            }
            client.put(localFile, remoteFileName, remoteTargetDirectory, mode);

            //閲嶅懡鍚�
            ch.ethz.ssh2.Session sess = conn.openSession();
            String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
            String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
            sess.execCommand("mv " + remoteFileName + " " + newPathName);//閲嶅懡鍚嶅洖鏉�

            conn.close();
        } catch (IOException ex) {
            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 鑾峰彇杩炴帴
     *
     * @return
     */
    public Connection getConn() throws Exception {
        if (conn == null) {
            conn = new Connection(ip, port);
        }
        conn.connect();
        //鐧诲綍
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false) {
            log.error("authentication failed");
            throw new Exception("authentication failed");
        }
        return conn;
    }

    /**
     * 涓婁紶鏂囦欢
     * @param conn                  scp杩炴帴
     * @param localFile
     * @param remoteFileName
     * @param remoteTargetDirectory
     * @param mode
     * @return sess   浼氳瘽
     * @throws Exception
     */
    public void putFile(Connection conn, String localFile, String remoteFileName, String remoteTargetDirectory, String mode) throws Exception {
        SCPClient client = new SCPClient(conn);
        if ((mode == null) || (mode.length() == 0)) {
            mode = "0600";
        }
        //寮�鍚細璇�
        Session sess = conn.openSession();
        client.put(localFile, remoteFileName, remoteTargetDirectory, mode);

        //閲嶅懡鍚�
//        ch.ethz.ssh2.Session sess = conn.openSession();
        String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
        String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
        sess.execCommand("mv " + remoteFileName + " " + newPathName);//閲嶅懡鍚嶅洖鏉�
        sess.close();
    }

    /**
     * 鑾峰彇鏃ュ織鍚嶇О鍒楄〃
     *
     * @return
     */
    public List<String> getLogName(String path) {
        List<String> logNames=null;
        Session sess=null;
        try {
            logNames=new ArrayList<String>();
            sess = conn.openSession();
            sess.execCommand("find " + path + " -name '*' ");
            InputStream stdout = sess.getStdout();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stdout));
            int i = 0;
            while (true) {
                String lineInfo = bufferedReader.readLine();
                if (lineInfo != null) {
                    log.info("lineInfo:"+lineInfo+",fileNum:"+i);
                    int lastIndex = lineInfo.lastIndexOf("/");
                    String logname=lineInfo.substring(lastIndex+1);
                    log.info("deal complete name:"+logname);
                    logNames.add(logname);
                } else {
                    break;
                }
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("find log name error:",e);
        }finally {
            if (sess!=null){
                sess.close();
            }
        }
        return logNames;

    }

}

